#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#define THREAD_NUM 2000
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

int sum = 0;

void *sum_func(void *arg)
{
    pthread_mutex_lock(&mutex);
    if (sum < 100)
    {
        sum++;
    }
    pthread_mutex_unlock(&mutex);
}

int main(int argc, char *argv[])
{
    /* 利用多线程进行i累加操作 */
    pthread_t thread_id[THREAD_NUM];

    for (int i = 0; i < THREAD_NUM; i++)
    {
        pthread_create(&thread_id[i], NULL, sum_func, NULL);
    }

    sleep(2);
    printf("sum = %d\n", sum);
    pthread_mutex_destroy(&mutex);

    return 0;
}